/*
 * Copyright 2008-2011 Wyld Collective / Obx Labs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/**
 * FlickrFeed
 *
 * This example shows how to get an image feed from Flickr, which
 * is return as a syndicated feed. The sketch fetches images
 * from the Twitter api, prints out its entries to the console, and continues
 * pulling entries from the feed at interval if any are available.
 */

//romefeeder
import com.wyldco.romefeeder.*;
import com.sun.syndication.feed.synd.*;

Feeder feeder;         // the feeder
SyndEntry entry;       // a feed entry

//array of thumbnail images loaded from flickr
PImage images[] = new PImage[50];
int imgCount = 0;

void setup() {
  //create the feeder
  feeder = new Feeder(this);

  //turn on output to the console (useful for debugging)
  feeder.verbose = true;

  //set sort by published date
  //default is unsorted (i.e. as ordered in the feed)
  feeder.sortByPublishedDate();

  //if you are exporting your sketch to an applet
  //set the proxy to bypass applet domain limitations
  //make sure you copy the proxy.php provided in the
  //data folder of example SimpleUrlFeed to your applet directory
  //feeder.setProxy("http://[urlToApplet]/FlickrFeed/applet/proxy.php");
  
  //set the update interval to check for new posts in the loaded feed(s)
  feeder.setUpdateInterval(5*60*1000); // milliseconds
  
  //start updating
  feeder.startUpdate();
    
  //load the feed  
  String tag = "jackalope";
  feeder.load("http://api.flickr.com/services/feeds/photos_public.gne?tags=" + tag + "&amp;lang=en-us&amp;format=rss_200");
}

void draw() {
  //display the next entries
  while (feeder.hasNext()) {
    //get the next entry
    entry = feeder.next();
    println("\n" + entry.getTitle());

    //extract the photokey from the content tag
    //this is used to build the urls to the different image sizes
    SyndContent content = (SyndContent)entry.getContents().get(0);
    String photokey = getPhotoKey(content.getValue());

    //get the link to the original image size
    //there are usually more than one link tag so parse for the
    //good one (enclosure)
    List links = entry.getLinks();  
    ListIterator it = links.listIterator();
    SyndLink link;
    while(it.hasNext()) {
      link = (SyndLink)it.next();
      if (link.getRel().equals("enclosure")) {
        //load the image square thumbnail using the original url and photokey
        images[imgCount] = loadImage(buildPhotoUrl(link.getHref(), photokey, "square"));
        //fill up the array and then stop looking
        if (++imgCount >= images.length) {
          feeder.stopUpdate();          
          return;
        }
      }
    }
  }
  
  //go through and draw loaded images
  if (imgCount > 0) {
  	imageMode(CENTER);
  	image(images[(frameCount%60)%imgCount], width/2, height/2);
  }
}

//this function helps getting the photoKey of the thumbnails so that all
//the URLs are correct.  getPhotoKey  gets a chunk of the feed and extracts
//the keys and characters you need for the links
String getPhotoKey(String content) {
  int iHttp = content.indexOf("http://", content.indexOf("http://", content.indexOf("http://")));
  int iUnderscore = content.indexOf('_', iHttp)+1;
  return content.substring(iUnderscore, iUnderscore+10);
}

//build the url to the specific photo
String buildPhotoUrl(String origUrl, String photoKey, String photoSize) {
  //map of size names to size postfixes
  HashMap sizes = new HashMap();
  sizes.put("square", "_s");
  sizes.put("thumbnail", "_t");
  sizes.put("small", "_m");
  sizes.put("medium", "");
  sizes.put("large", "_b");
  sizes.put("original", "_o");

  photoSize = photoSize.toLowerCase();
  if (!sizes.containsKey(photoSize))
    photoSize = "square";

  if (photoSize != "original")
    return origUrl.substring(0, origUrl.length()-16) + photoKey + sizes.get(photoSize) + ".jpg";
  else
    return origUrl;
}
